package Controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import Model.AccountDB;
import Model.Post;
import Model.PostDB;
import com.jspsmart.upload.SmartUpload;
import net.sf.json.JSONObject;

/**
 * Created by FreyrWings on 2017/5/24.
 * Json api for requests of single post
 */
public class PostController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/JavaScript; charset=utf-8");

        int accountid;
        if(req.getSession().getAttribute("token")!=null){// identify the account first
            String token = req.getSession().getAttribute("token").toString();
            accountid = AccountDB.identify(token);
            if(accountid == 0){
                return;
            }
        }
        else{
            return;
        }
        int id = Integer.parseInt(req.getParameter("id"));
        Post post = PostDB.retrieve(id);

        JSONObject jsonObject = new JSONObject();
        JSONObject postObj = new JSONObject();
        postObj.put("id", post.getId());
        postObj.put("title", post.getTitle().replaceAll(">", "&gt;").replaceAll("<", "&lt;"));
        postObj.put("image", post.getImage());
        postObj.put("description", post.getDescription().replaceAll(">", "&gt;").replaceAll("<", "&lt;"));
        postObj.put("date", post.getDate());
        postObj.put("auth", post.getAccountid()==accountid);
        postObj.put("author", AccountDB.getUsername(post.getAccountid()));
        jsonObject.put("post",postObj);
        resp.getWriter().write(jsonObject.toString());
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Integer accountid = 0;
        if(req.getSession().getAttribute("token")!=null){// identify the account first
            String token = req.getSession().getAttribute("token").toString();
            accountid = AccountDB.identify(token);
            if(accountid == 0){
                return;
            }
        }

        SmartUpload su = new SmartUpload();
        //初始化
        su.initialize(this.getServletConfig(), req, resp);
        boolean haspic = true;
        String picname = "";
        try {
            su.upload();
            picname = su.getFiles().getFile(0).getFileName();

            su.save("img");
        }
        catch (Exception e){
            e.printStackTrace();
        }
        if(picname.equals("")){
            haspic = false;
        }
        String type = su.getRequest().getParameter("type");

        if(type == null){
            System.out.println("null");
            return;
        }
        if(type.equals("init")){
            try {

                Post post = new Post();
                post.setTitle(su.getRequest().getParameter("title"));
                if(haspic){
                    post.setImage(picname);
                }
                post.setDescription(su.getRequest().getParameter("description"));
                post.setAccountid(accountid);
                PostDB.create(post);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        else if(type.equals("edit")&&
                PostDB.retrieve(Integer.parseInt(su.getRequest().getParameter("id"))).getAccountid()==accountid){// check the authentication
            try {
                Post post = new Post();
                post.setId(Integer.parseInt(su.getRequest().getParameter("id")));
                post.setTitle(su.getRequest().getParameter("title"));
                if(haspic){
                    post.setImage(picname);
                }
                post.setDescription(su.getRequest().getParameter("description"));
                PostDB.modify(post);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        resp.sendRedirect("/home");
    }
    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try{
            int id = Integer.parseInt(req.getParameter("id"));
            PostDB.delete(id);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}
